import Vue from 'vue'
import Router from 'vue-router'

// using router middleware
Vue.use(Router)

// import view components
import ViewIndex from '@/views/index'
import ViewDetail from '@/views/detail'
import ViewLogin from '@/views/login'
import ViewNew from '@/views/new'
import ViewPayment from '@/views/payment'
import ViewCardList from '@/views/cardList'
import ViewBindCard from '@/views/bindCard'
import ViewPaymentResult from '@/views/paymentResult'
import ViewPaymentConfirm from '@/views/paymentConfirm'

// create routes
const router = new Router({
	routes: [{
		name: 'home',
		path: '/',
		component: ViewIndex,
	}, {
		name: 'detail',
		path: '/detail/:id',
		component: ViewDetail
	}, {
		name: 'login',
		path: '/login',
		component: ViewLogin
	}, {
		name: 'new',
		path: '/new',
		component: ViewNew
	}, {
		name: 'payment',
		path: '/payment/:id/:amount',
		component: ViewPayment,
	},{
		name: 'payment-list',
		path: '/payment/list/:id/:amount',
		component: ViewCardList,
	}, {
		name: 'payment-new',
		path: '/payment/new/:id/:amount',
		component: ViewBindCard,
	}, {
		name: 'payment-confirm',
		path: '/payment/confirm/:id/:amount/:mobile',
		component: ViewPaymentConfirm,
	}, {
		name: 'payment-result',
		path: '/payment/result/:id/:amount',
		component: ViewPaymentResult,
	}, {
		name: '404',
		path: '*',
		redirect: '/'
	}]
})

// check token in cookie
import {hasToken, clearToken} from '@/assets/token'

router.beforeEach(async (to, from, next) => {
	if (to.name !== 'login' && hasToken()){
		next()
	} else if (to.name === 'login' && !hasToken()) {
		next()
	} else {
		await clearToken()
		next('/login')
	}
})

export default router
